package com.luo.ssm.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Properties;

/**
 * @author : luocheng
 * @date : Created in 2021/8/24 18:13
 * @description : Spring的配置类
 */
@Configuration
@ComponentScan("com.luo.ssm.service")
@MapperScan("com.luo.ssm.mapper")
@Import(com.luo.ssm.config.DataSourceConfig.class)
@EnableTransactionManagement
public class SpringConfig {
    //注册事务管理器
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DruidDataSource druidDataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(druidDataSource);
        return dataSourceTransactionManager;
    }
    //由于整合了mybatis，需要注册SqlSessionFactoryBean
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DruidDataSource druidDataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(druidDataSource);
        //给entity包下的类统一设置类名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.luo.ssm.entity");
        //指定mapper.xml映射文件的路径
        Resource[] mapperLocations={new ClassPathResource("mappers/SysFileMapper.xml"),new ClassPathResource("mappers/SysFolderMapper.xml")};
        sqlSessionFactoryBean.setMapperLocations(mapperLocations);
        //设置分页插件
        Interceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect","mysql");
        pageInterceptor.setProperties(properties);
        Interceptor[] interceptors={pageInterceptor};
        sqlSessionFactoryBean.setPlugins(interceptors);
        return sqlSessionFactoryBean;
    }
}
